package com.monitorRoutine.monitorRoutineServer.clt;

import com.alibaba.fastjson.JSON;
import com.monitorRoutine.monitorRoutineServer.entity.ControlCommandFile;
import com.monitorRoutine.monitorRoutineServer.entity.ControlCommandSet;
import com.monitorRoutine.monitorRoutineServer.service.ControlCommandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/controlCommand")
@Api(tags = "命令 API")
public class ControlCommandController {
    @Autowired
    ControlCommandService controlCommandService;
    @Value("${file.savePath}")
    String SAVE_PATH;
    @PostMapping
    @ApiOperation(value = "命令-添加")
    public boolean addKeyword(@RequestBody ControlCommandSet controlCommandSet) throws IOException {
        controlCommandService.saveControlCommand(controlCommandSet);
        return true;
    }
    @PostMapping("/file")
    @ApiOperation(value = "命令-文件-添加")
    public String handleFileUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("type") String type, // 这里添加了文件类型参数

            @ModelAttribute ControlCommandSet controlCommandSet) {

        if (!(type.equals("1")||type.equals("2"))) {
            return "类型错误";
        }


        if (file.isEmpty()) {
            return "请选择一个文件进行上传";
        }
        String fileName=null;
        try {
            // 文件保存逻辑
            fileName = file.getOriginalFilename()+"_"+ UUID.randomUUID().toString();
            // 确保上传目录存在，如果不存在则创建
            File uploadDir = new File(SAVE_PATH);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            // 将文件保存到上传目录
            File destinationFile = new File(uploadDir, fileName);
            file.transferTo(destinationFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败: " + e.getMessage();
        }
        controlCommandSet.setComman(controlCommandSet.getComman());

        controlCommandService.saveControlCommand(controlCommandSet,fileName,type);


        // 返回上传成功的消息，并包含其他参数
        return "文件上传成功: " + file.getOriginalFilename() + "，其他参数：param1=" + controlCommandSet.getComman() + ", param2=";
    }
    @GetMapping
    @ApiOperation(value = "命令-测试")
    public boolean addKeyword( ) throws IOException {
        controlCommandService.scanCommandDatabase();
        return true;
    }
}
